using System.Diagnostics;
using AzureContrib.WindowsAzure.Properties;
using Microsoft.WindowsAzure.StorageClient;

namespace AzureContrib.WindowsAzure.StorageClient
{
	/// <summary>
	/// Extension methods for <see cref="CloudBlobContainer"/>
	/// </summary>
	public static class CloudBlobContainerExtensions
	{
		/// <summary>
		/// Does the <see cref="CloudBlobContainer"/> exist in blob storage?
		/// </summary>
		/// <param name="cloudBlobContainer">The container to search for.</param>
		/// <returns>True if the container exists in blob storage.</returns>
		public static bool Exists(this CloudBlobContainer cloudBlobContainer)
		{
			try
			{
				cloudBlobContainer.FetchAttributes();
				return true;
			}
			catch (StorageClientException e)
			{
				if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
				{
					Trace.TraceInformation(Strings.BlobDoesNotExist, cloudBlobContainer.Uri.AbsoluteUri);
					return false;
				}

				Trace.TraceError(Strings.LocatingBlobThrewException, cloudBlobContainer.Uri.AbsoluteUri, e.GetType(), e.Message);
				throw;
			}
		}
	}
}